/*
 *This file will contain all the functions that have to do with
 communicating with the command socket.  These functions will be handled by
 thread 1.
 */

#include "cmdSockFuncs.h"

void *cmdSocketCom(void *notUsed)
{
	
	RESP *tmpR;  //will be used when getting the size of the file through an ftp command
	char *strPtr; //used for strtok_r

	for(;;)
	{

		pthread_cond_wait(&t0AndT1BufRdy, &mT0AndT1);

		
	
		if(shouldExit)
			break;


		//used to store the ftp command (will be used if file is being downloaded)
		char ftpCmd[strlen(t0AndT1Buf->message) + 1]; 

		//copy the ftp command in to the local variable
		strcpy(ftpCmd, t0AndT1Buf->message);
		t0AndT1Buf = sendAndReceive(t0AndT1Buf->message, -1);

		
		pthread_cond_signal(&t0AndT1BufRdy);
		pthread_mutex_unlock(&mT0AndT1);

		if(needsDataSock && t0AndT1Buf->code == C_DATARDY)
		{
			pthread_mutex_lock(&dummyMutex);

			//if downloading a file
			if(strstr(ftpCmd, "RETR "))
			{
				strtok_r(ftpCmd, " ", &strPtr);
				char *fileName = strtok_r(NULL, " ", &strPtr);

				
								/*
				sprintf(ftpCmd, "SIZE %s", fileName);
				//get the size of the file
				if(!(tmpR = sendAndReceive(ftpCmd, C_SIZE)))
				{
					perror("Failed to get file size");
					exit(1);
				}

				strtok_r(tmpR->message, " ", &strPtr);
				char *sizeStr = strtok_r(NULL, " ", &strPtr);

				pthread_mutex_lock(&mFileSize);
				fileSize = atoi(sizeStr);
				pthread_mutex_unlock(&mFileSize);
				*/

			}

			else{
				//pthread_cond_wait(&enterPasvMode, &dummyMutex);
				t0AndT1Buf = sendAndReceive(NULL, -1);
			}
					pthread_cond_wait(&enterPasvMode, &dummyMutex);
			pthread_mutex_unlock(&dummyMutex);

			enterPassiveMode();
			needsDataSock = false;
			pthread_cond_signal(&t0AndT1BufRdy);
		}
		else
			needsDataSock = false;

	}
	close(cmd_socket);
	cmd_socket = -1;
	
	pthread_exit(NULL);
	return NULL;
}


